package com.joe.demo.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import lombok.extern.slf4j.Slf4j;

/**
 * @Description netty hello world
 * @Author gaojw
 * @Date 2024-08-29
 */
@Slf4j
public class HelloServer {

    public static void main(String[] args) {
        // 1. 启动器，负责组装 netty 组件，启动服务器
        new ServerBootstrap()
                // 2. BossEventLoop WorkerEventLoop   EventLoop => (selector, thread), group 组
                .group(new NioEventLoopGroup())
                // 3. 选择 服务器 ServerSocketChannel 实现
                .channel(NioServerSocketChannel.class)
                // 4. boss 负责处理连接，worker child 负责处理读写 决定了worker child 能执行哪些操作 handler
                .childHandler(
                        // 5. channel 代表和客户端进行数据读写的通道 Initializer 初始化，负责添加别的handler
                        new ChannelInitializer<NioSocketChannel>() {
                            /**
                             * 连接建立后被调用
                             * @param nioSocketChannel
                             * @throws Exception
                             */
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        // 6. 添加具体的handler 将BytBuf 转为 字符串
                        nioSocketChannel.pipeline().addLast(new StringDecoder());
                        // 自定义 handler
                        nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            /**
                             * 读事件
                             * @param ctx
                             * @param msg
                             * @throws Exception
                             */
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                log.info("接收到的消息：{}", msg);
                            }
                        });
                    }
                })
                // 7. 绑定端口
                .bind(8080);
    }
}
